package com.snow.component;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.snow.starter.SnowAutoConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;
import java.util.Date;
@Slf4j
@ConditionalOnProperty(value = "snow.file-storage-type", havingValue = "local")
@Component
public class FileStorageComponent implements IStorageComponent {

    final SnowAutoConfiguration snowAutoConfiguration;


    public FileStorageComponent(SnowAutoConfiguration snowAutoConfiguration) {
        log.info("文件存储模式：local");
        this.snowAutoConfiguration = snowAutoConfiguration;
    }

    /**
     *
     * @param fileInputStream 保存文件流
     * @param fileName 文件名称
     * @return 保存地址
     */
    @Override
    public String save(InputStream fileInputStream, String fileName, boolean isPublic) {
        String savePath = snowAutoConfiguration.getFileSavePath() + DateUtil.format(new Date(), "yyyy/MM/dd/") + RandomUtil.randomString(6) + fileName.substring(fileName.lastIndexOf('.'));
        saveByPath(fileInputStream, savePath);
        return savePath;
    }

    @Override
    public String getPreviewUrl(String fileName) {
        return fileName.replace(snowAutoConfiguration.getFileSavePath(), snowAutoConfiguration.getFilePreviewPrefix());
    }

    @Override
    public InputStream getObject(String savePath) {
        return FileUtil.getInputStream(savePath);
    }

    private void saveByPath(InputStream fileInputStream, String savePath) {
        File file = FileUtil.touch(savePath);
        FileUtil.writeFromStream(fileInputStream, file);
    }
}
